package com.sinszm.common;

import com.google.gson.GsonBuilder;
import com.sinszm.common.exception.ApiError;
import com.sinszm.common.exception.SystemApiError;

/**
 * 统一返回值对象
 *
 * @author chenjianbo
 */
public class Response<T> {

    private static final String MESSAGE = "SUCCESS";

    /**
     * 状态
     * <desc>
     *     true:成功
     *     false:失败
     * </desc>
     */
    private Boolean state;

    /**
     * 请求消息内容
     */
    private String message;

    /**
     * 返回值对象
     */
    private T body;

    /**
     * 异常栈
     */
    private Throwable cause;

    private Response() {
    }

    public Boolean getState() {
        return state;
    }

    private void setState(Boolean state) {
        this.state = state;
    }

    public String getMessage() {
        return message;
    }

    private void setMessage(String message) {
        this.message = message;
    }

    public T getBody() {
        return body;
    }

    private void setBody(T body) {
        this.body = body;
    }

    public Throwable getCause() {
        return cause;
    }

    private void setCause(Throwable cause) {
        this.cause = cause;
    }

    /**
     * 成功返回
     * @param body  返回值
     * @param <T>   类型
     * @return 响应
     */
    public synchronized static <T> Response<T> success(T body) {
        Response<T> response = new Response<>();
        response.setState(true);
        response.setMessage(MESSAGE);
        if (body != null) {
            response.setBody(body);
        }
        response.setCause(null);
        return response;
    }

    /**
     * 失败返回
     * @param apiError  错误代码
     * @param cause     异常栈
     * @return 响应
     */
    public synchronized static Response<Object> fail(ApiError apiError, Throwable cause) {
        Response<Object> response = new Response<>();
        response.setState(false);
        response.setMessage(
                apiError.message() == null ? SystemApiError.SYSTEM_ERROR_01.message() : apiError.message()
        );
        response.setCause(cause);
        response.setBody(null);
        return response;
    }

    /**
     * 自定义失败信息组装
     * @param body
     * @param msg
     * @param <T>
     * @return 响应
     */
    public synchronized static <T> Response<T> fail(T body, String msg) {
        Response<T> response = new Response<>();
        response.setState(false);
        response.setMessage(msg == null ? SystemApiError.SYSTEM_ERROR_01.message() : msg);
        response.setCause(null);
        response.setBody(body);
        return response;
    }

    @Override
    public String toString() {
        return new GsonBuilder()
                .create()
                .toJson(this);
    }
}
